#!/bin/bash

echo "请输入要设置的Bootloader密码："
read -s password

if [ -z "$password" ]; then
    echo "密码不能为空"
    exit 1
fi

# 生成加密密码
echo "正在生成加密密码..."
password_output=$(echo -e "$password\n$password" | grub2-mkpasswd-pbkdf2 2>&1)

if [ $? -ne 0 ]; then
    echo "密码哈希生成失败"
    echo "详细错误：$password_output"
    exit 1
fi

# 正确提取密码哈希（从包含 grub.pbkdf2 的行中提取）
password_hash=$(echo "$password_output" | grep "grub.pbkdf2" | awk '{print $NF}')

if [ -z "$password_hash" ]; then
    echo "无法提取密码哈希"
    echo "grub2-mkpasswd-pbkdf2 输出：$password_output"
    exit 1
fi

echo "生成的密码哈希：$password_hash"

# 备份grub配置
cp /etc/grub.d/40_custom /etc/grub.d/40_custom.bak 2>/dev/null || true

# 添加密码配置到grub
cat <<EOF >> /etc/grub.d/40_custom
set superusers="root"
password_pbkdf2 root $password_hash
EOF

# 创建user.cfg文件
echo "创建/boot/grub2/user.cfg文件"
# 备份现有文件
[ -f /boot/grub2/user.cfg ] && cp /boot/grub2/user.cfg /boot/grub2/user.cfg.bak

# 创建user.cfg文件
cat > /boot/grub2/user.cfg <<EOF
GRUB2_PASSWORD=$password_hash
EOF
echo "密码配置已写入/boot/grub2/user.cfg"

# 更新grub配置
grub2-mkconfig -o /boot/grub2/grub.cfg

echo "Bootloader密码已设置完成"
